package com.topnav.mc.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.js.lib.result.Result;
import com.js.lib.utils.ResultUtil;
import com.topnav.mc.admin.bean.OrgTreeSelectBean;
import com.topnav.mc.admin.entity.Authorization;
import com.topnav.mc.admin.entity.Organization;
import com.topnav.mc.admin.entity.RoleAuthorization;
import com.topnav.mc.admin.entity.UserOrganizaiton;
import com.topnav.mc.admin.entity.bean.AuthorizationBean;
import com.topnav.mc.admin.entity.bean.DeviceBean;
import com.topnav.mc.admin.entity.bean.RoleAuthorizationBean;
import com.topnav.mc.admin.entity.param.AuthorizationParam;
import com.topnav.mc.admin.entity.param.RoleAuthorizationParam;
import com.topnav.mc.admin.entity.wrapper.AuthorizationWrapper;
import com.topnav.mc.admin.security.PermissionGrade;
import com.topnav.mc.admin.service.IAuthorizationService;
import com.topnav.mc.admin.service.IRoleAuthorizationService;
import com.topnav.mc.admin.service.IUserOrganizaitonService;
import com.topnav.mc.base.mc.McController;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ExceptionUtil;
import com.topnav.mc.uitls.PermissionGradeUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: kenny
 * @Date: 2024/2/27 10:37
 */
@RestController
@CrossOrigin
@RequestMapping("admin/authorization")
public class AuthorizationController extends McController<Authorization, AuthorizationBean, AuthorizationParam,
        IAuthorizationService, AuthorizationWrapper> {

    @Resource
    private PermissionGradeUtil permissionGradeUtil;
    @Autowired
    private IRoleAuthorizationService roleAuthorizationService;
    @Resource
    private PermissionGradeUtil pmGradeUtil;
    @Autowired
    private IUserOrganizaitonService userOrganizaitonService;
    @Autowired
    private IAuthorizationService authorizationService;

    /**
     * 深度查询所有菜单, 并组成树结构的数据
     * @return
     */
    //@ApiOperation(value = "深度查询所有机构")
    @GetMapping("/query/depthChildrens")
    @ResponseBody
    public Result queryDepthChildrens(){
        PermissionGrade permissionGrade = pmGradeUtil.getPmGrade();
        if (permissionGrade.getPermissionLevel() >= 9){
            //超级系统管理员返回全部菜单
            List<Authorization> list =authorizationService.list();
            return Result.ok(this.changeToTree(list));
        }
        //根据当前用户的登录部门的权限来界定
        LambdaQueryWrapper<UserOrganizaiton> urWrapper = new  LambdaQueryWrapper<UserOrganizaiton>()
                .eq(UserOrganizaiton::getUserId,permissionGrade.getUserId()).eq(UserOrganizaiton::getOrgId,permissionGrade.getOrgId());
        UserOrganizaiton uo = userOrganizaitonService.getOne(urWrapper,false);
        if (uo == null || uo.getRoleId() == null){
            //没有数据返回
            throw ExceptionUtil.commonException(ExceptionMsg.ERROR_NOT_DATA_EXCEPTION);
        }

        QueryWrapper<RoleAuthorizationParam> raWwrapper = new QueryWrapper<RoleAuthorizationParam>();
        raWwrapper.eq("ra.role_id",uo.getRoleId());
        raWwrapper.orderByAsc("a.at_path");
        List<RoleAuthorizationBean> list = roleAuthorizationService.listInfo(raWwrapper);
        if (CollectionUtils.isEmpty(list)){
            //没有数据返回
            throw ExceptionUtil.commonException(ExceptionMsg.ERROR_NOT_DATA_EXCEPTION);
        }
        List<Authorization> authList = new ArrayList<>();
        for(RoleAuthorizationBean ra : list) {
            Authorization a = new Authorization();
            a.setId(ra.getAuthId());
            a.setAtCode(ra.getAuthName());
            a.setAtName(ra.getAuthName());
            a.setAtPath(ra.getAuthPath());
            a.setHasChild(true);
        }
        return Result.ok(this.changeToTree(authList));
    }

    /**
     * 换成树形结构
     * @param list
     * @return
     */
    private List<OrgTreeSelectBean> changeToTree(List<Authorization> list) {
        List<OrgTreeSelectBean> result = new ArrayList<>();
        //转MAP
        Map<Long, Authorization> map = list.stream().collect(Collectors.toMap(Authorization::getId, (p) -> p));
        for (Authorization a : list) {
            if (a.getParentId() == null) {
                OrgTreeSelectBean bean = new OrgTreeSelectBean()
                        .setId(a.getId().toString())
                        .setLabel(a.getAtName())
                        .setPath(a.getAtPath());
                bean.getArrt().put("code", a.getAtCode());
                bean.getArrt().put("name", a.getAtName());
                result.add(bean);
                this.recursive(bean,map);
            }
        }
        return result;
    }

    private void recursive(OrgTreeSelectBean parent,Map<Long, Authorization> map) {
        LambdaQueryWrapper<Authorization> wrapper = new LambdaQueryWrapper<Authorization>().eq(Authorization::getParentId,parent.getId());
        List<Authorization> list = authorizationService.list(wrapper);
        for(Authorization a:list) {
            //是存在此权限
            if (map.get(a.getId())==null) {
                continue;
            }
            OrgTreeSelectBean bean = new OrgTreeSelectBean()
                    .setId(a.getId().toString())
                    .setLabel(a.getAtName())
                    .setPath(a.getAtPath());
            bean.getArrt().put("code", a.getAtCode());
            bean.getArrt().put("name", a.getAtName());
            if (parent.getChildren() == null){
                parent.setChildren(new ArrayList<OrgTreeSelectBean>());
            }
            parent.getChildren().add(bean);

            this.recursive(bean,map);
        }
    }

}
